package priv.stones.controller.administrate;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import priv.stones.common.exception.StonesException;
import priv.stones.common.utils.Result;
import priv.stones.common.utils.ServletHelper;
import priv.stones.controller.administrate.shiro.ShiroUtils;
import priv.stones.entity.SysAdmin;
import priv.stones.entity.SysLoginLog;
import priv.stones.service.SysLoginLogService;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;

/**
 * @Author: Stones
 * @Description:
 * @Date: 2017/10/9 14:39
 */
@Controller
@RequestMapping("/administrate/gate")
public class GateController {

    @Autowired
    private Producer producer;
    @Autowired
    private SysLoginLogService sysLoginLogService;

    /**
     * 登录
     *
     * @return
     */
    @RequestMapping("/login")
    public String Login() {
        Subject currentUser = ShiroUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            return "redirect:/administrate";
        }
        return "/administrate/login";
    }

    /**
     * 验证
     *
     * @param username
     * @param password
     * @param kaptcha
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/login/check", method = RequestMethod.POST)
    @ResponseBody
    public Result CheckLogin(HttpServletRequest request, String username, String password, String kaptcha) {
        //正确验证码
//        String rightKaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
//        if (!rightKaptcha.equalsIgnoreCase(kaptcha)) {
//            throw new StonesException("验证码不正确");
//        }
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            token.setRememberMe(true);
            ShiroUtils.getSubject().login(token);
            SysAdmin currAdmin = ShiroUtils.getAdmin();
            if (currAdmin.getStatus() == 2) {
                ShiroUtils.Logout();
                //账号被禁用
                throw new StonesException("账号已禁用");
            } else {
                if (!currAdmin.getName().equals(ShiroUtils.SuperAdmin)) {
                    //记录登录日志
                    UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
                    SysLoginLog sysLoginLog = new SysLoginLog();
                    sysLoginLog.setAdmin(currAdmin.getId());
                    sysLoginLog.setIp(ServletHelper.getIpAddress(request));
                    sysLoginLog.setBrowser(userAgent.getBrowser().getName());
                    sysLoginLog.setOs(userAgent.getOperatingSystem().getName());
                    sysLoginLog.setLogintime(new Date());
                    sysLoginLogService.insert(sysLoginLog);
                }
            }
        } catch (UnknownAccountException e) {
            throw new StonesException("账号不存在");
        } catch (IncorrectCredentialsException e) {
            throw new StonesException("账号或密码不正确");
        } catch (AuthenticationException e) {
            throw new StonesException("账户验证失败");
        }
        return Result.Ok();
    }

    /**
     * 验证码
     *
     * @param response
     * @throws IOException
     */
    @RequestMapping("/login/captcha.jpg")
    public void Captcha(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    /**
     * 退出
     *
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public Result Logout() {
        ShiroUtils.Logout();
        return Result.Ok();
    }

}
